﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command;
using B.S.BasicData.Api.Read.Application.Command.RBAC;
using B.S.BasicData.Domian.Entities;
using B.S.BasicData.Domian.Entities.RBAC;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.RBAC
{
    public class DelUserHandler : IRequestHandler<DelUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UserModel> userRepo;
        private readonly IMapper mapper;

        public DelUserHandler(IBaseRepository<UserModel>userRepo,IMapper mapper)
        {
            this.userRepo = userRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(DelUserCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();
            var user = userRepo.GetValue(request.UserId).Result;
            if (user == null)
            {
                res.Message = "用户名不存在";
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
            }
            var entity = mapper.Map<UserModel>(user);
            entity.IsDel = true;
            var r = userRepo.Update(entity).Result;
            if (r > 0)
            {
                res.Message = "删除成功";
                res.Code = ApiEnum.Ok;
                res.Data = r;
            }
            else
            {
                res.Message = "删除失败";
                res.Code = ApiEnum.Error;
                res.Data = r;
            }
            return Task.FromResult(res);
        }
    }
}
